#include "activeservicemanager.h"
#include "service.h"

#include "../utils/logger.h"

ActiveServiceManager *ActiveServiceManager::m_instance = 0;

QMutex ActiveServiceManager::m_mutex;

ActiveServiceManager::ActiveServiceManager()
{
    LOG_DEBUG("init service manager");
    //m_mutex =

    m_activeServiceList = new QMap< std::string,  Service*>();

   // m_mutex = new QMutex();
}

ActiveServiceManager::~ActiveServiceManager()
{
    //delete m_mutex;

    if(m_activeServiceList != NULL)
    {
        if(!m_activeServiceList->empty())
        {
            QMap< std::string, Service*>::iterator i = m_activeServiceList->begin();
            QMap< std::string, Service*>::iterator j = i;
            while( i != m_activeServiceList->end())
            {
                j = m_activeServiceList->erase(i);
                delete i.value();

                i = j;
            }
            // remove error
        }

        delete m_activeServiceList;
    }
}

int ActiveServiceManager::removeRunningService( std::string service_name)
{
    QMutexLocker locker(&m_mutex);

    QMap< std::string, Service*>::iterator i = m_activeServiceList->find(service_name);
    if( i == m_activeServiceList->end())
    {
        return -1;
    }
    int count = m_activeServiceList->remove(service_name);
    if(count >1)
    {
        // 2 more has same session id
        // can not happen
        return -2;
    }

    delete i.value();
    return 0;
}

int ActiveServiceManager::addRunningService(Service *service)
{
    QMutexLocker locker(&m_mutex);

    LOG_DEBUG("add running service");
    if(m_activeServiceList == NULL)
    {
        return -1;
    }

    QMap< std::string, Service*>::iterator i = m_activeServiceList->find(service->getServiceName());
    if(i != m_activeServiceList->end())
    {
        //check why has same id
        // this can not happen
        return -1;
    }

    m_activeServiceList->insert(service->getServiceName(), service);

    return 0;
}

Service *ActiveServiceManager::getServiceByName( std::string service_name)
{

    if(m_activeServiceList != NULL)
    {
        LOG_DEBUG("get running service by name : %s", service_name.c_str());
        return (*m_activeServiceList)[service_name];
    }
    return NULL;
}

bool ActiveServiceManager::hasRunningService()
{
}
